package com.ksyzt.ksite2.client.news;

import java.sql.Timestamp;
import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.ksyzt.gwt.client.common.ImageUploader;
import com.ksyzt.gwt.client.common.MessageComposite;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.gwt.client.event.MessageHandler;
import com.ksyzt.gwt.client.ui.button.Switch;
import com.ksyzt.gwt.client.ui.richeditor.EditOption;
import com.ksyzt.gwt.client.ui.richeditor.XhEditor;
import com.ksyzt.ksite2.client.column.ColumnSelector;
import com.ksyzt.ksite2.client.common.AttatchmentManager;
import com.ksyzt.ksite2.client.common.ServerProxy;
import com.ksyzt.ksite2.shared.OrgType;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObjs;
import com.ksyzt.ksite2.shared.modle.COLUMNObj;
import com.ksyzt.ksite2.shared.modle.NEWSObj;
import com.ksyzt.ksite2.shared.modle.VW_NEWSObj;

public class NewsEditor extends MessageComposite {

	private static NewsEditorUiBinder uiBinder = GWT
			.create(NewsEditorUiBinder.class);

	interface NewsEditorUiBinder extends UiBinder<Widget, NewsEditor> {
	}

	AttatchmentManager attm;

	String m_upload_iamge = "";
	private MessageHandler m_image_uploader = new MessageHandler() {

		@Override
		public void onMessage(Object sender, Integer message, Object value) {
			if (message == MessageEvent.SUCCESS) {
				String path = (String) value;
				if (m_vw_news != null && m_vw_news.getID() != null) {
					NEWSObj n = new NEWSObj();
					n.setID(m_vw_news.getID());
					n.setICON(path);
					ServerProxy.SYS_MANAGER.submitNews(n,
							m_on_news_handler_noreturn);
				} else {
					m_upload_iamge = path;
				}
			} else if (message == MessageEvent.DELETE) {
				// 清空ICON
				if (m_vw_news != null && m_vw_news.getID() != null) {
					NEWSObj n = new NEWSObj();
					n.setID(m_vw_news.getID());
					n.setICON("");
					ServerProxy.SYS_MANAGER.submitNews(n,
							m_on_news_handler_reset_icon);
				} else {
					m_upload_iamge = "";
					imagePreview.setImage(null);
					imagePreview.reset();
				}
			} else if (message == MessageEvent.MESSAGE) {
				message((String) value);
			}
		}
	};
	DateTimeFormat m_df = DateTimeFormat.getFormat("yyyy年MM月dd日 HH:mm:ss");
	@UiField
	DateBox date;

	public NewsEditor() {
		initWidget(uiBinder.createAndBindUi(this));

		imagePreview.addMessageHandler(m_image_uploader);

		date.setFormat(new DateBox.DefaultFormat(m_df));

	}

	@UiField
	CheckBox checkSHOWTIME;
	@UiField
	Switch btnLasted;

	@UiField
	Switch btnTopup;

	@UiField
	TextBox txtRANKVAL;

	@UiField
	TextBox txtAUTHOR;
	@UiField
	TextBox txtDUTYAUTHOR;

	@UiField
	Label lbVIEWER;
	@UiField
	ImageUploader imagePreview;

	private static final String TAG = "NEWS";
	VW_NEWSObj m_vw_news;
	Integer m_oid;

	private AsyncCallback<ATTACHMENTObjs> m_attatchment_handler = new AsyncCallback<ATTACHMENTObjs>() {

		@Override
		public void onSuccess(ATTACHMENTObjs result) {
			if (result.size() == 0) {
				lbInfo.setText("该新闻还没有附件");
			} else {
				lbInfo.setText("该新闻已有附件:" + result.size() + "个");
			}
		}

		@Override
		public void onFailure(Throwable caught) {
			lbInfo.setText("不能获取附件信息");

		}
	};

	public void edit(VW_NEWSObj n, int oid) {
		message("");
		m_vw_news = n;
		m_oid = oid;
		toPage();
		if (n == null) {
			btnAttatchemnt.setEnabled(false);
			btnCopy.setEnabled(false);
		} else {
			btnAttatchemnt.setEnabled(true);
			btnCopy.setEnabled(true);
		}
	}

	private NEWSObj fromPage() {
		NEWSObj n = new NEWSObj();
		Date d = date.getValue();

		if (m_vw_news != null) {
			n.setID(m_vw_news.getID());

		} else {
			n.setOID(m_oid);
			n.setICON(m_upload_iamge);
		}
		n.setTITLE(txtTITLE.getValue());
		n.setCONTENT(editor.getSource());
		n.setDISPLAY(checkDISPLAY.getValue() == true ? 1 : 0);
		n.setLINK(txtLINK.getValue());
		n.setSUMMARY(txtSUMMARY.getValue());
		n.setORIGION(txtORIGION.getValue());
		n.setSHOWTIME(checkSHOWTIME.getValue()==true?1:0);
		n.setRANKVAL(Integer.valueOf(txtRANKVAL.getValue()));
		n.setAUTHOR(txtAUTHOR.getValue());
		n.setADDTIME(new Timestamp(d.getTime()));
		n.setDUTYAUTHOR(txtDUTYAUTHOR.getValue());
		n.setLASTED(btnLasted.getValue() == true ? 1 : 0);
		n.setUPTOP(btnTopup.getValue() == true ? 1 : 0);
		return n;
	}

	private void toPage() {
		if (m_vw_news == null) {

			txtTITLE.setValue("输入标题");
			txtLINK.setValue("");
			txtSUMMARY.setValue("");
			txtORIGION.setValue("本站");
			editor.setSource("");
			// txtTAG.setValue("");
			checkDISPLAY.setValue(true);
			imagePreview.setImage(null);
			txtRANKVAL.setValue("0");
			txtAUTHOR.setValue("佚名");
			lbVIEWER.setText("浏览0次");
			txtDUTYAUTHOR.setValue("责编");
			checkSHOWTIME.setValue(true);

			date.setValue(new Date());
			btnLasted.setValue(false);
			btnTopup.setValue(false);

			lbInfo.setText("没有附件");

		} else {
			txtTITLE.setValue(m_vw_news.getTITLE());
			txtLINK.setValue(m_vw_news.getLINK());
			txtSUMMARY.setValue(m_vw_news.getSUMMARY());
			txtORIGION.setValue(m_vw_news.getORIGION());
			editor.setSource(m_vw_news.getCONTENT());
			// txtTAG.setValue(m_vw_news.getTAG());
			txtRANKVAL.setValue(m_vw_news.getRANKVAL() + "");
			checkDISPLAY.setValue((m_vw_news.getDISPLAY() == null || m_vw_news
					.getDISPLAY() > 0) ? true : false);

			if (m_vw_news.getICON() != null && m_vw_news.getICON().length() > 0) {
				imagePreview.setImage(GWT.getModuleBaseURL() + "../"
						+ m_vw_news.getICON());
			} else {
				imagePreview.setImage(null);
			}
			checkSHOWTIME.setValue(m_vw_news.getSHOWTIME()>0?true:false);
			
			txtAUTHOR.setValue(m_vw_news.getAUTHOR());
			lbVIEWER.setText("浏览" + m_vw_news.getVIEWER() + "次");
			date.setValue(new Date(m_vw_news.getADDTIME().getTime()));
			txtDUTYAUTHOR.setValue(m_vw_news.getDUTYAUTHOR());
			btnLasted.setValue(m_vw_news.getLASTED() > 0);
			btnTopup.setValue(m_vw_news.getUPTOP() > 0);
			lbInfo.setText("获取附件信息....");
			ServerProxy.SYS_MANAGER.getAttatchments("NEWS" + m_vw_news.getID(),
					m_attatchment_handler);
		}
	}

	@UiField
	TextBox txtTITLE;
	@UiField
	TextBox txtLINK;
	@UiField
	TextArea txtSUMMARY;
	@UiField
	Switch checkDISPLAY;

	@UiField
	TextBox txtORIGION;
	@UiField
	Button btnSubmit;

	@UiField
	Label lbInfo;
	@UiField
	Button btnCopy;
	@UiField
	Label lbMessage;

	@UiField
	XhEditor editor;

	private AsyncCallback<VW_NEWSObj> m_on_news_handler = new AsyncCallback<VW_NEWSObj>() {

		public void onSuccess(VW_NEWSObj result) {
			message("提交成功");
			if (btnReturn.isEnabled()) {
				onReturn(null);
			} else {
				edit(result, m_oid);
			}
		}

		public void onFailure(Throwable caught) {

			message(caught.getMessage());
		}
	};

	private AsyncCallback<VW_NEWSObj> m_on_news_handler_reset_icon = new AsyncCallback<VW_NEWSObj>() {

		public void onSuccess(VW_NEWSObj result) {
			message("清空图片成功");
			m_upload_iamge = "";
			imagePreview.setImage(null);
			imagePreview.reset();
		}

		public void onFailure(Throwable caught) {

			message(caught.getMessage());
		}
	};

	private AsyncCallback<VW_NEWSObj> m_on_news_handler_noreturn = new AsyncCallback<VW_NEWSObj>() {

		public void onSuccess(VW_NEWSObj result) {
			message("修改图片成功");
			m_upload_iamge = "";
			imagePreview.setImage(GWT.getModuleBaseURL() + "../"
					+ result.getICON());
			imagePreview.reset();
			edit(result, m_oid);
		}

		public void onFailure(Throwable caught) {

			message(caught.getMessage());
		}
	};

	@UiHandler("btnSubmit")
	void onSubmit(ClickEvent e) {
		NEWSObj n = fromPage();
		ServerProxy.SYS_MANAGER.submitNews(n, m_on_news_handler);
	}

	@UiField
	Button btnReturn;

	@UiHandler("btnReturn")
	void onReturn(ClickEvent e) {

		MessageEvent ev = new MessageEvent(MessageEvent.RETURN, 0);
		fireEvent(ev);
	}

	public void enableReturn(boolean b) {
		btnReturn.setEnabled(b);
	}

	@UiField
	Button btnAttatchemnt;
	PopupPanel g_popup;

	private MessageHandler m_att_handler = new MessageHandler() {

		@Override
		public void onMessage(Object sender, Integer message, Object value) {
			if (message == MessageEvent.CANCEL) {
				g_popup.hide();
			}
		}
	};

	private AsyncCallback<VW_NEWSObj> m_copy_handler = new AsyncCallback<VW_NEWSObj>() {

		@Override
		public void onSuccess(VW_NEWSObj result) {
			Window.alert("内容已复制");
			if (dlg != null) {
				dlg.hide(true);
			}
		}

		@Override
		public void onFailure(Throwable caught) {
			message(caught.getMessage());
			if (dlg != null) {
				dlg.hide(true);
			}

		}
	};

	private MessageHandler m_select_column_handler = new MessageHandler() {

		@Override
		public void onMessage(Object sender, Integer message, Object value) {
			if (message == MessageEvent.OK) {
				COLUMNObj col = (COLUMNObj) value;
				NEWSObj n = fromPage();
				n.setOID(col.getID());
				n.setID(null);
				ServerProxy.SYS_MANAGER.submitNews(n, m_copy_handler);
			} else if (message == MessageEvent.CANCEL) {
				if (dlg != null) {
					dlg.hide(true);
				}
			}

		}
	};

	@UiHandler("btnAttatchemnt")
	void onAttatchemntClick(ClickEvent e) {
		if (g_popup == null) {
			g_popup = new PopupPanel();
			attm = new AttatchmentManager();
			attm.addMessageHandler(m_att_handler);
			g_popup.setWidget(attm);
			g_popup.setAutoHideEnabled(true);
		}
		attm.initControl(TAG, m_vw_news.getID());
		g_popup.showRelativeTo(btnAttatchemnt);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.google.gwt.user.client.ui.Composite#onAttach()
	 */
	@Override
	protected void onAttach() {
		super.onAttach();
		EditOption option = EditOption.create();
		option.width("100%");
		option.height("500px");
		option.setSkin(EditOption.SKIN_NOSTYLE);
		option.tools(EditOption.TS_FULL);
		option.setLinkExt(EditOption.LINK_EXT);
		String upload_path = GWT.getModuleBaseURL() + "../gwtfileuploader";
		String editRoot = GWT.getModuleBaseURL() + "../js/editor/";
		option.setUploadImagePath(upload_path);
		option.setUploadLinkExt(upload_path);
		option.setEditorRoot(editRoot);
		option.setUrlBase( GWT.getModuleBaseURL() + "../");
		editor.initControl(option);
	}

	ColumnSelector dlg = null;

	@UiHandler("btnCopy")
	void onCopy(ClickEvent e) {
		dlg = new ColumnSelector();

		dlg.addMessageHandler(m_select_column_handler);
		dlg.show();
		dlg.center();
		dlg.init(userid, OrgType.OT_NEWS);
	}

	int userid;

	public void setUserId(int uid) {
		userid = uid;
	}
}
